package com.upcode.weighing.log;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.upcode.weighing.domain.SysLogs;
import com.upcode.weighing.domain.SysOptLog;
import com.upcode.weighing.service.SysOptLogService;
import com.upcode.weighing.util.ClientRequestInfoUtil;
import com.upcode.weighing.util.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class SysLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(SysLogAspect.class);

    @Autowired
    private SysOptLogService sysOptLogService;

    @Pointcut("@annotation(com.upcode.weighing.log.OpsLog)")
    public void logPoinCut() {
    }

    @Before("logPoinCut()")
    public void saveOperation(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        OpsLog opsLog=method.getAnnotation(OpsLog.class);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURL = request.getRequestURL().toString();//请求路径，暂时未用到
        SysOptLog s=new SysOptLog();
        //s.setId(IdWorker.getId());//生成ID
        s.setCreateUser(SecurityUtils.getCurrentUserName());//操作用户
        s.setLoginName(SecurityUtils.getCurrentUserUsername());//账号
        s.setIp(ClientRequestInfoUtil.getClientIp(request));//ip
        s.setType(opsLog.type());//操作类型
        s.setDesc(opsLog.operation());//详情
        s.setExceptionLog("");//异常记录
        s.setCreateTime(LocalDateTime.now());//创建时间
        sysOptLogService.addSysLogs(s);
    }
}
